export default class {
    private cache ?: Cache;

    async init(){
        if(this.cache) return this.cache
        this.cache = await caches.open('hls-cache');

        return this.cache
    }

    async get(key: string) {
        const cache = await this.init();
        const response = await cache.match(key);
        if(!response) return null

        if(response.headers.get('Content-Type')?.includes('arraybuffer')){
            return response.arrayBuffer();
        }

        return response.arrayBuffer();
    }

    async put(key: string, data: any) {
        const cache = await this.init();

        const headers = {}

        if(!(data instanceof ArrayBuffer)){
            headers['Content-Type'] = 'text/plain';
            headers['Content-Length'] = new TextEncoder().encode(data).byteLength;
        }else{
            headers['Content-Type'] = 'application/arraybuffer';
            headers['Content-Length'] = data.byteLength;
        }
        
        await cache.put(key, new Response(data, {headers}));
    }



}